/**
 * 
 */
package cn.ad.server.web.servlet.v2.parser;

import cn.ad.server.common.utils.Decrypter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * Adview Winotice解析
 * @author Wu Chengjun
 */
public class AdviewWinoticeRequestParser extends DefaultWinoticeRequestParser {
	
	/**
	 * encryption key (32 bytes - provided at account set up)
	 */
	private String ekey;

	/**
	 * integrity key (32 bytes - provided at account set up)
	 */
	private String ikey;
	
	/*
	 * (non-Javadoc)
	 * @see cn.falconnect.adserver.adapter.DefaultWinoticeRequestParser#parseWinPrice(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public double parseWinPrice(HttpServletRequest request) throws ParameterParseExcption{
		String winPrice = getWinoticePriceParam(request);
		double price = 0.0d;
		if(StringUtils.isNoneEmpty(winPrice) && StringUtils.isNotBlank(winPrice)){
			BigDecimal bd = new BigDecimal(decryptWinPrice(winPrice, ekey, ikey));
			price = bd.divide(new BigDecimal(10000 * 1000)).doubleValue();
		}else{
			throw new ParameterParseExcption(DefaultWinoticeRequestParser.PARAM_WINOTICE_PRICE, null, "解析Adview winprice出现异常: win_price is null");
		}
		return price;
	}
	
	
	/**
	 * win_price价格解析，
	 * Adview 的bid win_price价格解析采用GOOGLE标准协议，
	 * 因此加密解析算法可以参考https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-price?hl=zh-CN
	 * @param encPrice
	 * @param ekey
	 * @param ikey
	 * @return
	 */
	private long decryptWinPrice(String encPrice, String ekey, String ikey) {
		byte[] bytes = Decrypter.decryptSafeWebStringToByte(encPrice, ekey, ikey);
		long value = 0;
		try(DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes))) {
			value = dis.readLong();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}

	/**
	 * @return the ekey
	 */
	public String getEkey() {
		return ekey;
	}

	/**
	 * @param ekey the ekey to set
	 */
	public void setEkey(String ekey) {
		this.ekey = ekey;
	}

	/**
	 * @return the ikey
	 */
	public String getIkey() {
		return ikey;
	}

	/**
	 * @param ikey the ikey to set
	 */
	public void setIkey(String ikey) {
		this.ikey = ikey;
	}
}
